package com.czmh.etc.onlinepubsys.jy.utils;


import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static com.czmh.etc.onlinepubsys.jy.utils.IHttpHelper.ResponseDTO.CLIENT_ERROR_CODE;
import static com.czmh.etc.onlinepubsys.jy.utils.IHttpHelper.ResponseDTO.RESP_SERIALIZE_FAIL;

/**
 * @author chen_yang
 */
@Component
public class OkHttpImpl implements IHttpHelper {

    private static final Logger LOGGER = LoggerFactory.getLogger(OkHttpImpl.class);

    private int connectTimeout = 75, writeTimeout = 60, readTimeout = 60;
    private OkHttpClient httpClient;

    private MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    public OkHttpImpl() {
        //请求超时时间设置
        this.connectTimeout = connectTimeout == 0 ? 75 : connectTimeout;
        this.writeTimeout = writeTimeout == 0 ? 60 : writeTimeout;
        this.readTimeout = readTimeout == 0 ? 60 : readTimeout;

        httpClient = new OkHttpClient.Builder()
                .connectTimeout(connectTimeout, TimeUnit.SECONDS)
                .readTimeout(readTimeout, TimeUnit.SECONDS)
                .writeTimeout(writeTimeout, TimeUnit.SECONDS)
                .build();
    }

    @Override
    public ResponseDTO post(RequestDTO requestDTO) {
        ResponseDTO responseDTO = new ResponseDTO();

        //requset
        if (StringUtils.isBlank(requestDTO.data)) {
            LOGGER.error("post req data is empty");
            return responseDTO.setCode(CLIENT_ERROR_CODE).setMsg(ResponseDTO.EMPTY_REQ_DATA);
        }

        Request request = new Request.Builder()
                .url(requestDTO.url)
                .post(RequestBody.create(JSON, requestDTO.data))
                .build();

        //response
        Response response = null;
        try {
            response = httpClient.newCall(request).execute();

            if (response == null) {
                return responseDTO.setCode(ResponseDTO.SERVER_NO_RESP).setMsg(ResponseDTO.SEND_REQ_FAIL);
            }
            return copyResponse(response);
        } catch (IOException e) {
            LOGGER.error("URL[{}] DATA[{}] post exception", requestDTO.url, requestDTO.data, e);
            return responseDTO.setCode(ResponseDTO.SERVER_NO_RESP).setMsg(ResponseDTO.SEND_REQ_FAIL);
        }
    }

    /**
     * 复制okhttp response 应答对象
     *
     * @param response okhttp response
     * @return 成功 code =200,data=应答序列化json string 失败code=420,data =null
     */
    private ResponseDTO copyResponse(Response response) {
        ResponseDTO responseDTO = new ResponseDTO();
        responseDTO.setCode(response.code());
        try {
            String data =
                    response.isSuccessful() ? response.body().string() : null;
            responseDTO.setData(data);
        } catch (IOException e) {
            LOGGER.error("http client resp serialize fail", e);
            responseDTO.setCode(CLIENT_ERROR_CODE);
            responseDTO.setMsg(RESP_SERIALIZE_FAIL);
            responseDTO.setErrorMsg(e.getMessage());
        }
        return responseDTO;
    }
}
